package com.zhoug.common.http.interceptors;



import com.zhoug.common.http.core.BaseResponse;
import com.zhoug.common.utils.LogUtils;
import com.zhoug.common.utils.StringUtils;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * token拦截器
 *
 * @Author HK-LJJ
 * @Date 2019/12/6
 * @Description
 */
public class TokenInterceptor implements Interceptor {
    private static final String TAG = ">>>TokenInterceptor";
    private static final String TOKEN="token";
    private static final String STATE="state";

    @Override
    public Response intercept(Chain chain) throws IOException {

       /* //创建新的请求添加cookie
         LogUtils.d(TAG, "http request:" + chain.request().url().toString());
        okhttp3.Request.Builder builder = chain.request().newBuilder();
        Set<String> cookies = SingleDataManager.get().getCookie();
        if (cookies != null) {
            for (String cookie : cookies) {
                builder.addHeader("Cookie", cookie);
            }
        }

        //请求返回的Response中有cookie则保存（登陆页面有cookie）
        Response originalResponse = chain.proceed(builder.build());
        //登录页面返回cookie
        List<String> headers = originalResponse.headers("Set-Cookie");
        if (!headers.isEmpty()) {
            HashSet<String> cookie = new HashSet<>(headers);
            SingleDataManager.get().setCookie(cookie);
        }*/
       //新请求添加参数
       /* Request request = chain.request();
        Request newRequest = addParam(request);
        String  url=newRequest.url().toString();
        LogUtils.d(TAG, "intercept url:"+url);
        //返回
        Response response = chain.proceed(newRequest);
        boolean successful = response.isSuccessful();
        if(successful){
            //成功
            if(response.code()== BaseResponse.STATUS_SUCCESS){
                //是登录,读取token并保存
                if(url.contains(RequestMethods.loginUrl)){
                    LogUtils.d(TAG, "intercept:登录接口");
                    //保存token
                    ResponseBody body = response.body();
                    if(body!=null){
                        byte[] bytes = body.bytes();
                        String json = new String(bytes, "UTF-8");
                        try {
                            JSONObject jsonObject=new JSONObject(json);
                            int state =0 ;//登录成功状态
                            try {
                                state=Integer.parseInt(jsonObject.optString(STATE));
                            } catch (NumberFormatException e) {
                                e.printStackTrace();
                            }
                            if(state==BaseResponse.STATUS_SUCCESS){
                                LogUtils.d(TAG, "intercept:登录成功");
                                String token = jsonObject.optString(TOKEN);
                                if(!StringUtils.isEmpty(token)){
                                    LogUtils.d(TAG, "intercept:保存token="+token);
                                    SingleDataManager.get().setToken(token);
                                }else{
                                    LogUtils.d(TAG, "intercept:token="+token);
                                }
                            }else{
                                LogUtils.e(TAG, "intercept:登录失败");
                            }


                        } catch (Exception e) {
                            LogUtils.e(TAG, "intercept:e="+e.getMessage());
                            e.printStackTrace();
                        }
                        // 这里值得注意。由于前面value.bytes()把响应流读完并关闭了，所以这里需要重新生成一个response，
                        // 否则数据就无法正常解析了
                        Response newResponse = response.newBuilder()
                                .body(ResponseBody.create(MediaType.parse(Constant.HTTP_JsonType),bytes))
                                .build();
//                        LogUtils.d(TAG, "intercept:newResponse="+newResponse);
                        return newResponse;
                    }

                }

            }else if(response.code()== BaseResponse.STATUS_COOKIE_TIME_OUT){
                LogUtils.d(TAG, "intercept:登录过期");
                //请求重定向,重新登录

            }

        }

//        LogUtils.d(TAG, "intercept:response"+response.toString());

        return response;*/

       return null;

    }

    /**
     * 添加统一参数
     * @param oldRequest
     * @return
     */
    private Request addParam(Request oldRequest) {
       /* String token = SingleDataManager.get().getToken();
        if (token != null) {
            HttpUrl.Builder builder = oldRequest.url()
                    .newBuilder()
                    .setEncodedQueryParameter("token", token);
            Request newRequest = oldRequest.newBuilder()
                    .method(oldRequest.method(), oldRequest.body())
                    .url(builder.build())
                    .build();
            return newRequest;

        }

        return oldRequest;*/
       return null;

    }

}
